package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则Service业务层处理
 * 
 * @author zzyl_mh
 * @date 2025-08-26
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private AlertDataServiceImpl alertDataService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 设备报警数据的数据过滤的定时任务
     */
    @Override
    public void alertFilter() {
        // 1.查询所有规则
        if (this.lambdaQuery().eq(AlertRule::getStatus, 1).count() <= 0) {
            // 1.1 没有直接返回
            return;
        }
        // 2.查询所有设备上报的数据
        List<List<DeviceData>> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if(CollUtil.isEmpty(values)){
            // 2.1 没有直接返回
            return;
        }
        // 3.开始遍历数据,处理每一条数据,是否满足报警规则
        List<DeviceData> allDeviceData = new ArrayList<>();
        values.forEach(allDeviceData::addAll);
        allDeviceData.forEach(data -> dataAlertFilter(data));
    }

    private void dataAlertFilter(DeviceData data) {
        // 1.如果当前上报的数据超过1分钟,无效数据,直接结束
        if(data.getAlarmTime().plusMinutes(1).isBefore(LocalDateTime.now())){
            return;
        }
        // 2.查询产品下设备对应的物模型规则
        List<AlertRule> alertRules = this.lambdaQuery()
                .eq(AlertRule::getProductKey, data.getProductKey())
                .in(AlertRule::getIotId, -1, data.getIotId())
                .eq(AlertRule::getStatus,1)
                .eq(AlertRule::getFunctionId, data.getFunctionId()).list();
        // 3.判断规则是否为空,为空则直接结束
        if(CollUtil.isEmpty(alertRules)){
            return;
        }
        // 4.开始遍历规则,判断上报数据是否满足规则
        alertRules.forEach(rule ->  dataIsMatchRule(rule,data));

    }

    /**
     * 判断上报数据是否满足规则
     * @param rule
     * @param data
     */
    private void dataIsMatchRule(AlertRule rule, DeviceData data) {
        String durationKey= CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + data.getProductKey() + "_" + data.getIotId() + "_" + data.getFunctionId() + "_" + rule.getId();
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + data.getProductKey() + "_" + data.getIotId() + "_" + data.getFunctionId() + "_" + rule.getId();

        // 1.判断上报时间是否在规则的开始时间和结束时间之间
        if(!alarmTimeMatch(rule,data)){
            return;
        }
        // 2.检查上报数据是否达到阈值
        if(!dataValueMatch(rule,data)){
            //未达到阈值 , 删除redis中的报警数
            redisTemplate.delete(durationKey);
            return;
        }
        // 3.判断是否有沉默周期,有直接结束
        String clientKey = (String) redisTemplate.opsForValue().get(silentKey);
        if(StrUtil.isNotBlank(clientKey)){
            return;
        }
        // 4.查询redis中的报警数,如果没有设置为1,有则加1
        Integer durationCount = (Integer) redisTemplate.opsForValue().get(durationKey);
        if(ObjUtil.isNull(durationCount)){
            durationCount = 1;
        }else {
            durationCount ++;
        }
        // 5.判断报警数是否达到持续周期,未达到,将报警数更新回redis,直接结束
        if(ObjUtil.notEqual(durationCount,rule.getDuration())){
            redisTemplate.opsForValue().set(durationKey,durationCount);
            return;
        }
        // 6.redis删除报警数,添加沉默周期
        redisTemplate.delete(durationKey);
        redisTemplate.opsForValue().set(silentKey,"1", rule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        // 7.批量添加报警数据
        batchInsertAlertData(rule,data);

    }

    /**
     * 批量添加报警数据
     * @param rule
     * @param data
     */
    private void batchInsertAlertData(AlertRule rule, DeviceData data) {
        // 1.获取需要通知的人员集合
        List<Long> adminList = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        List<Long> othorIds = new ArrayList<>();
        if(rule.getAlertDataType() == 0){
            // 老人异常数据
            if(data.getLocationType() == 0){
                // 随身设备
                othorIds = deviceMapper.selectNursingIdsByIotIdWithElder(data.getIotId());
            }else{
                // 床位
                othorIds = deviceMapper.selectNursingIdsByIotIdWithBed(data.getIotId());
            }
        }else{
            // 设备异常数据
            othorIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        Collection<Long> userIds = CollUtil.addAll(adminList, othorIds);
        userIds.remove(null);
        // 2.批量添加报警数据
        List<AlertData> alertDataList = new ArrayList<>();
        userIds.forEach(userId -> {
            AlertData alertData = BeanUtil.copyProperties(data, AlertData.class, "id");
            alertData.setAlertRuleId(rule.getId());
            String reason = StrUtil.format("报警原因：{}{}{}+持续{}周期+聚合周期", rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
            alertData.setAlertReason(reason);
            alertData.setType(rule.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(userId);
            alertDataList.add(alertData);
        });
        alertDataService.saveBatch(alertDataList);
        // 3.报警通知
        websocketNotify(alertDataList.get(0), rule , userIds);
    }

    /**
     * 报警通知
     * @param alertData
     * @param rule
     * @param userIds
     */
    private void websocketNotify(AlertData alertData, AlertRule rule, Collection<Long> userIds) {
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setVoiceNotifyStatus(0);
        alertNotifyVo.setNotifyType(1);
        if(alertData.getLocationType() == 1 && alertData.getPhysicalLocationType() == 2){
            alertNotifyVo.setIsAllConsumer(true);
        }else {
            alertNotifyVo.setIsAllConsumer(false);
        }
        webSocketServer.sendMessageToConsumer(alertNotifyVo, userIds);
    }

    /**
     * 判断上报数据是否达到阈值
     * @param rule
     * @param data
     * @return
     */
    private boolean dataValueMatch(AlertRule rule, DeviceData data) {
        Object dataValue = data.getDataValue();
        try {
            Double value = Double.valueOf(dataValue.toString());
            Double ruleValue1 = rule.getValue();
            if(">=".equals(rule.getOperator()) && Double.compare(value, ruleValue1) < 0
                || "<".equals(rule.getOperator()) && Double.compare(value, ruleValue1) >= 0){

                return false;
            }
        } catch (NumberFormatException e) {
            return false;
        }

        return true;
    }

    /**
     * 判断上报时间是否在规则的开始时间和结束时间之间 不在 false 在 true
     * @param rule
     * @param data
     * @return
     */
    private boolean alarmTimeMatch(AlertRule rule, DeviceData data) {
        String[] split = rule.getAlertEffectivePeriod().split("~");
        LocalTime start = LocalTime.parse(split[0]);
        LocalTime end = LocalTime.parse(split[1]);
        LocalTime alarmTime = data.getAlarmTime().toLocalTime();
        if(alarmTime.isBefore(start) || alarmTime.isAfter(end)){
            return false;
        }
        return true;
    }
}
